// const sha512 = require("js-sha512");

// var arrayBuffer = sha512.arrayBuffer('Message to hash');
// console.log(arrayBuffer);
let n = document.querySelector("#n");
let Q = document.querySelector("#Q");
let PU = document.querySelector(".gongyao");
let PR = document.querySelector(".siyao");
let miwen = document.querySelectorAll(".miwen");
let jiami = document.querySelector(".jiami");
let jiemi = document.querySelector(".jiemi")

let jiemingwen = document.querySelector(".jiemingwen");


// 执行加密算法的点击事件
jiami.addEventListener("click", function() {
    let p = Number(document.querySelector("#p").value);
    let q = Number(document.querySelector("#q").value);
    let e = Number(document.querySelector("#e").value);
    let M = Number(document.querySelector("#M").value);
    console.log("p：", p);
    console.log("q：", q);
    console.log("e：", e);
    console.log("M", M)
    RSAAlgorithm(p, q, e, M)
});



// 执行解密算法的点击事件
jiemi.addEventListener("click", function() {
    let inpmiwen = Number(document.querySelector("#inpmiwen").value);
    let inpnnn = Number(document.querySelector("#inpnnn").value)
    let miyao = Number(document.querySelector("#miyao").value);

    jiemisuanfa(BigInt(inpmiwen), BigInt(miyao), BigInt(inpnnn));
});


// 加密算法
function RSAAlgorithm(p, q, e, M) {
    // nnn为n
    // ddd为d
    // CCC为密文C
    let nnn = p * q;
    console.log("nnn：", nnn);
    let ddd = 0
    let QQQ = (p - 1) * (q - 1);
    for (let a = 0; a < 1000; a++) {
        if (e * a % QQQ == 1) {
            ddd = a;
            break;
        }
    }
    console.log("ddd：", ddd)
    if (ddd <= 0) {
        alert("找不到对应的d！")
    }

    let CCC = Math.pow(M, e) % nnn;
    console.log("CCC：", CCC)

    n.innerHTML = nnn;
    Q.innerHTML = QQQ;
    PU.innerHTML = `{${e},${nnn}}`;
    PR.innerHTML = `{${ddd},${nnn}}`;
    miwen[0].innerHTML = CCC;
    miwen[1].innerHTML = CCC;


}


// 解密算法
function jiemisuanfa(C, ddd, n) {
    console.log("CCC：", C);
    console.log("ddd：", ddd);
    console.log("n：", n);
    let M = (C ** ddd) % n;
    console.log("M：", M);
    jiemingwen.innerHTML = M;
}